package panel.sinaWeiCo
{
	import assists.HtmlText;
	import assists.Lang;
	import assists.Scale9Grid;
	import assists.SizeManager;
	import assists.TextFieldUtils;
	import assists.URI;
	import assists.caches.JPGEncoder;
	import assists.resource.ResourceLoader;
	
	import flash.desktop.NativeApplication;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MediaEvent;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.geom.Matrix;
	import flash.media.CameraRoll;
	import flash.media.CameraUI;
	import flash.media.MediaPromise;
	import flash.media.MediaType;
	import flash.net.FileReference;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	import flash.utils.ByteArray;
	
	import inerface.ISinaWeiCo;
	
	import main.ClientConstants;
	import main.LocalStoreInfo;
	
	import panel.viewSpots.MenuDownSlide;
	import panel.viewSpots.navigation.BtnClouree;
	
	public class SinaWeiCoPanel extends Sprite implements ISinaWeiCo
	{
		private var _sinaBtn:Sprite = new Sprite();
		private var _qqBtn:Sprite = new Sprite();
		private var _loginBtn:BtnClouree;
		private var _cancelBtn:BtnClouree;
		private var _backGround:Bitmap;;
		private var _sendMessageTxt:TextField = new TextField();
		private var _titleTxt:TextField = new TextField();
		
		private var _stage:Stage;
		private var _loader:ResourceLoader;
		private var _lang:Lang;
		private var _uri:URI;
		private static const MESSAGE_END_CONTENT:String = "  打扰大家了，抱歉";

		private var _accountBack:Scale9Grid;
		private var _qq:QQWeibo;
		private var _sina:SinaWeibo;
		private var _weiboType:int;
		private var _camera:CameraUI;
		private static const WEIBO_QQ:int = 1;
		private static const WEIBO_SINA:int = 2;

		private var _mediaData:MediaPromise;
		private var _imageLoader:Loader;
		private var _file:FileReference;

		private var weiboPic:Sprite;
		
		private var _cameraBtn:Sprite = new Sprite();
		private var _addPicBtn:Sprite = new Sprite();
		private var _btnsGroup:Sprite = new Sprite();
		private var _camerallRoll:CameraRoll;
		private var _onClose:Function;
		
		private var _typeTxt:TextField = new TextField();
		private var _storeCach:LocalStoreInfo = new LocalStoreInfo();
		private var _faWeiboCallBack:Function;
		private var _scrollMenu:MenuDownSlide;
		private var _menuList:Array = [];
//		private var _rotateBtn:Sprite = new Sprite();
		
		public function SinaWeiCoPanel()
		{
			super();
		}
		
		public function init(stage:Stage,loader:ResourceLoader,lang:Lang,uri:URI = null):void
		{
			_stage = stage;
			_loader = loader;
			_lang = lang;
			_uri = uri;
			
			_qq = new QQWeibo(_stage);
			
			var topLine:Bitmap = _loader.uiManager.generateBmp(_loader.uiManager.whiteLineBack);
			var topScale:Scale9Grid = new Scale9Grid(topLine.bitmapData,10,10);
			topScale.width = _stage.stageWidth;
			
			_backGround = _loader.uiManager.generateBmp(_loader.uiManager.weiBoGround);
			_backGround.width = _stage.stageWidth;
			_backGround.height = _stage.stageHeight;
			
			_loginBtn = new BtnClouree();
			_loginBtn.label("发布");
			_loginBtn.autoSize(_stage.stageWidth * 0.25);
			
			_cancelBtn = new BtnClouree();
			_cancelBtn.label("取消");
			_cancelBtn.autoSize(_stage.stageWidth * 0.25);
			
			_sendMessageTxt.width = _backGround.width * 0.7;
			_sendMessageTxt.autoSize = "left";
			_sendMessageTxt.multiline = true;
			_sendMessageTxt.wordWrap = true;
			_sendMessageTxt.type = TextFieldType.INPUT;
			TextFieldUtils.setHtmlText(_sendMessageTxt,HtmlText.formatSizeColor("请再次输入您要分享的内容",0x999999));
			
			TextFieldUtils.setHtmlText(_titleTxt,HtmlText.formatSizeColor("分享",0xfff100,28),true,true);
			_titleTxt.autoSize = "left";
			_titleTxt.mouseEnabled = false;
			_titleTxt.x = (topScale.width - _titleTxt.width) * 0.5;
			_titleTxt.y = (topScale.height - _titleTxt.height) * 0.5;
			
			
			_sinaBtn.addChild(_loader.uiManager.generateBmp(_loader.uiManager.sinaWeibo));
			_qqBtn.addChild(_loader.uiManager.generateBmp(_loader.uiManager.qqWeibo));
			_sinaBtn.height = _sinaBtn.height * SizeManager.changeToAutosize(0.4,_sinaBtn.width);
			_sinaBtn.width = _stage.stageWidth * 0.4;
			
			_qqBtn.height = _qqBtn.height * SizeManager.changeToAutosize(0.4,_qqBtn.width);
			_qqBtn.width = _stage.stageWidth * 0.4;
			
			_sinaBtn.x = (_stage.stageWidth * 0.5 - _sinaBtn.width) * 0.5;
			_sinaBtn.y = _stage.stageHeight * 0.98 - _sinaBtn.height;
			_qqBtn.x = (_stage.stageWidth * 0.5 - _qqBtn.width) * 0.5 + _stage.stageWidth * 0.5;	
			_qqBtn.y = _sinaBtn.y;
			if(_qq.hasAuthored())
			{
			_qqBtn.filters = [];
			}else
			{
				_weiboType = 2;
				_qqBtn.filters = [ClientConstants.GLOBAL_FILTER_GREY];	
			}
			if(_storeCach.readInfo("sinaWeibo"))
			{
			_sinaBtn.filters = [];
			}else
			{
				_weiboType = _weiboType * 3;
				_sinaBtn.filters = [ClientConstants.GLOBAL_FILTER_GREY];	
			}
			
			_typeTxt.autoSize = "left";
			_typeTxt.mouseEnabled = false;
			TextFieldUtils.setHtmlText(_typeTxt,HtmlText.formatSizeColor("分享到",0xffffff),true,true);
			_typeTxt.y = _qqBtn.y - _typeTxt.height * 1.2;
			
			var line:Bitmap = _loader.uiManager.generateBmp(_loader.uiManager.cutLine,true);
		    line.width = _stage.stageWidth * 0.9;
			line.x = (_stage.stageWidth - line.width) * 0.5;
			line.y = _typeTxt.y - _stage.stageHeight * 0.02;
			
			_accountBack = new Scale9Grid(_loader.uiManager.generateBmp(_loader.uiManager.inputPng).bitmapData,10,10);
			_accountBack.width = _backGround.width * 0.9;
			_accountBack.height = _backGround.width * 0.4;
			_accountBack.x = (_backGround.width - _accountBack.width) * 0.5;
			_accountBack.y = topScale.height + _stage.stageHeight * 0.02;
			
			
			var cbmp:Bitmap = _loader.uiManager.generateBmp(_loader.uiManager.cameraPic);
			var pBmp:Bitmap = _loader.uiManager.generateBmp(_loader.uiManager.weiboPic);
			cbmp.width = cbmp.height = pBmp.width = pBmp.height = _stage.stageWidth * 0.3;
			_cameraBtn.addChild(cbmp);
			_addPicBtn.addChild(pBmp);
			_addPicBtn.x = (_stage.stageWidth * 0.5 - _addPicBtn.width) * 0.5;
			_cameraBtn.x = _addPicBtn.x +　_stage.stageWidth * 0.5;
			_addPicBtn.y = line.y - _addPicBtn.height - _stage.stageHeight * 0.02;
			_cameraBtn.y = _addPicBtn.y;
			_btnsGroup.addChild(_cameraBtn);
			_btnsGroup.addChild(_addPicBtn);
			
			var cameraDescTxt:TextField = new TextField();
			cameraDescTxt.mouseEnabled = false;
			cameraDescTxt.autoSize = "left";
			TextFieldUtils.setHtmlText(cameraDescTxt,HtmlText.formatSizeColor("照相",0xffffff,20),true,true);
			cameraDescTxt.x = _cameraBtn.x + (_cameraBtn.width - cameraDescTxt.width) * 0.5;
			cameraDescTxt.y = _cameraBtn.y - cameraDescTxt.height;
			
			var addPicDescTxt:TextField = new TextField();
			addPicDescTxt.mouseEnabled = false;
			addPicDescTxt.autoSize = "left";
			TextFieldUtils.setHtmlText(addPicDescTxt,HtmlText.formatSizeColor("相册",0xffffff,20),true,true);
			addPicDescTxt.x = _addPicBtn.x + (_addPicBtn.width - addPicDescTxt.width) * 0.5;
			addPicDescTxt.y = _addPicBtn.y - addPicDescTxt.height;
			
//			_rotateBtn.addChild(_loader.uiManager.generateBmp(_loader.uiManager.rotatePng));
//			_rotateBtn.width = _rotateBtn.height = _addPicBtn.width * 0.4;
//			_rotateBtn.x = _addPicBtn.width - _rotateBtn.width * 0.2;
//			_rotateBtn.y = - _rotateBtn.height * 0.8;
//			_rotateBtn.visible = false;
//			_rotateBtn.addEventListener(MouseEvent.CLICK,rotatePicHandler);
//			_addPicBtn.addChild(_rotateBtn);
			
			_accountBack.addChild(_sendMessageTxt);
			
			layout();
			this.addChild(_backGround);
			this.addChild(_sinaBtn);
			this.addChild(_qqBtn);
			this.addChild(topScale);
			this.addChild(_titleTxt);
			this.addChild(_loginBtn);
			this.addChild(_cancelBtn);
			this.addChild(_accountBack);
			this.addChild(_typeTxt);
			this.addChild(line);
			this.addChild(_btnsGroup);
			this.addChild(cameraDescTxt);
			this.addChild(addPicDescTxt);
		
			_accountBack.addEventListener(MouseEvent.CLICK,clearInputContentHandler);
			_loginBtn.addEventListener(MouseEvent.CLICK,loginHandler);
			_cancelBtn.addEventListener(MouseEvent.CLICK,cancelHandler);
			_cameraBtn.addEventListener(MouseEvent.CLICK,clickCameraHandler);
			_addPicBtn.addEventListener(MouseEvent.CLICK,addPicHandler);
			_sinaBtn.addEventListener(MouseEvent.CLICK,clickSinaHandler);
			_qqBtn.addEventListener(MouseEvent.CLICK,clickQQHandler);
		}
		
		protected function rotatePicHandler(event:MouseEvent):void
		{
			trace("rotate");
		}
		
		protected function clickQQHandler(event:MouseEvent):void
		{
			trace("qq");
			if(_storeCach.readInfo("qqWeibo")) return;
			_weiboType = WEIBO_QQ;
			bindWeibo();
		}
		
		protected function clickSinaHandler(event:MouseEvent):void
		{
			if(_storeCach.readInfo("sinaWeibo")) return;
			_weiboType = WEIBO_SINA;
			trace("sina");
			bindWeibo();
		}
		
		private function bindWeibo():void
		{
			if(_weiboType == WEIBO_QQ)
			{
				if(!_qq) _qq = new QQWeibo(_stage);
				_qq.executeMessage(authorCallBack);
			}else
			{
				if(!_sina) _sina = new SinaWeibo(_stage);
				_sina.executeMessage(authorCallBack);
			}
		}
		
		private function authorCallBack():void
		{
			if(_weiboType == WEIBO_QQ)
			{
                _qqBtn.filters = [];				
			}else
			{
				_sinaBtn.filters = [];
			}
		}
		
		protected function addPicHandler(event:MouseEvent):void
		{
			if(_imageLoader && _imageLoader.numChildren > 0)
			{
			   if(!_scrollMenu) 
			   {
			   _scrollMenu = new MenuDownSlide(_stage,_loader);
			   _menuList = [{desc:"移除图片",func:removeAddPic},{desc:"添加图片",func:addPic},{desc:"取消",func:clickScrollMenuHandler}];
			   this.addChild(_scrollMenu);
			   _scrollMenu.show(_menuList);
			   _scrollMenu.y = _stage.stageHeight;
			   }
			   if(_scrollMenu.moveState) return;
			   _scrollMenu.start();
			   _scrollMenu.addEventListener(MouseEvent.CLICK,clickScrollMenuHandler);
				return;
			}
			trace("addPIc");
			addPic();
		}
		
		protected function clickScrollMenuHandler(event:MouseEvent = null):void
		{
			_scrollMenu.removeEventListener(MouseEvent.CLICK,clickScrollMenuHandler);
			_scrollMenu.backMenu();
		}
		
		private function addPic():void
		{
			removeAddPic();
			if(!_camerallRoll)
			{
				_camerallRoll = new CameraRoll();
			}
			_camerallRoll.browseForImage();
			_camerallRoll.addEventListener(MediaEvent.SELECT,choosePicHandler);
		}
		
		private function removeAddPic():void
		{
			if(!_imageLoader || _imageLoader.numChildren == 0) return;
			if(_imageLoader && _imageLoader.parent)
			{
			_imageLoader.parent.removeChild(_imageLoader);
			_imageLoader.removeChildren();
			_imageLoader = null;
			}
			if(weiboPic && weiboPic.parent)
			{
			weiboPic.parent.removeChild(weiboPic);
			weiboPic = null;
			}
		}
		
		protected function choosePicHandler(event:MediaEvent):void
		{
			loadImageLoader(event.data);
		}
		
		protected function clickCameraHandler(event:MouseEvent):void
		{
             takePhoto();
		}
		
		protected function loginHandler(event:MouseEvent):void
		{
			trace("fabu");
			if(_weiboType == 6) return;
			this.mouseChildren = false;
			if(_mediaData)
			{
				if(weiboPic == null) return;
			}
			if(_qq.hasAuthored() && _storeCach.readInfo("sinaWeibo"))
			{
				_faWeiboCallBack = sendQQWeibo;
				sendSinaWeibo();
			}
			else if(_qq.hasAuthored())
			{
				sendQQWeibo();
			}
			else if(_storeCach.readInfo("sinaWeibo"))
			{
				sendSinaWeibo();
			}
		}
		
		private function sendQQWeibo():void
		{
			if(_mediaData)
			{
				_qq.sendWeibo(_sendMessageTxt.text + MESSAGE_END_CONTENT,sendWeiboSuccess,_file);
			}else
			{
				_qq.sendWeibo(_sendMessageTxt.text + MESSAGE_END_CONTENT,sendWeiboSuccess);
			}
		}
		
		private function sendSinaWeibo():void
		{
			if(!_sina) 
			{
				_sina = new SinaWeibo(_stage);
			}
			
			if(_mediaData)
			{
				var jpg:JPGEncoder = new JPGEncoder();
				var tempContainer:Sprite = new Sprite();
				tempContainer.addChild(_imageLoader);
				_imageLoader.x = 0;
				_imageLoader.y = 0; 
				var bdata:BitmapData = new BitmapData(tempContainer.width,tempContainer.height);
				bdata.draw(tempContainer);
				var byte:ByteArray = jpg.encode(bdata);
				_sina.sendWeibo(_sendMessageTxt.text + MESSAGE_END_CONTENT,sendWeiboSuccess,byte);
			}else
			{
				_sina.sendWeibo(_sendMessageTxt.text + MESSAGE_END_CONTENT,sendWeiboSuccess);
			}
			if(_faWeiboCallBack != null)
			{
			_faWeiboCallBack();
			}
		}
		
		private function sendWeiboSuccess():void
		{
			_weiboType = _weiboType - 3;
			if(_weiboType == 0) return;
			_mediaData = null;
			this.mouseChildren = true;
			var alert:ScreenLockPanel = new ScreenLockPanel(_stage);
			alert.endShow(HtmlText.formatSizeColor("微博发布成功！",0xfff100));
			this.addChild(alert);
	       removeAddPic();
			if(weiboPic && weiboPic.parent)
			{
				weiboPic.parent.removeChild(weiboPic);
				weiboPic = null;
			}
			if(_faWeiboCallBack != null)
			{
				_faWeiboCallBack();
				_faWeiboCallBack = null;
			}
		}
		
		protected function cancelHandler(event:MouseEvent):void
		{
			_onClose();
			trace("cancel");
		} 
		
		protected function clearInputContentHandler(event:MouseEvent):void
		{
			if(event.target == _cameraBtn || event.target == _addPicBtn) return;
			_accountBack.removeEventListener(MouseEvent.CLICK,clearInputContentHandler);
			var txtFormat:TextFormat = new TextFormat();
			txtFormat.color = 0;
			txtFormat.size = 18 + HtmlText.NUMBER_FONT_CHANGE;
			_sendMessageTxt.defaultTextFormat = txtFormat;
			_sendMessageTxt.text = "";
			_stage.focus = _sendMessageTxt;
		}
		
		private function layout():void
		{
			
			_sendMessageTxt.x = _accountBack.x + _accountBack.width * 0.05;
			
			_loginBtn.x = (_backGround.width * 0.5 - _loginBtn.width) * 0.5;
			_loginBtn.y =  _accountBack.y + _accountBack.height * 1.1; 
			
			_cancelBtn.x = _loginBtn.x + _backGround.width * 0.5;
			_cancelBtn.y = _loginBtn.y;
		}
		
		public function takePhoto():void
		{
			if(!CameraUI.isSupported) return;
			if(!_camera)
			{
				_camera = new CameraUI();
				_camera.addEventListener(MediaEvent.COMPLETE,onMediaComplete);
				_camera.addEventListener(ErrorEvent.ERROR,onMediaErro);
				_camera.addEventListener(Event.CANCEL,onCancelHandler);
			}
			_camera.launch(MediaType.IMAGE);	
		}
		
		protected function onCancelHandler(event:Event):void
		{
			trace("cancel");
		}
		
		protected function onMediaErro(event:ErrorEvent):void
		{
			trace("error" + event.errorID);
		}
		
		protected function onMediaComplete(event:MediaEvent):void
		{
			loadImageLoader(event.data);
		}
		
		private function loadImageLoader(value:MediaPromise):void
		{
			_mediaData = value;
			if(!_imageLoader) 
			{
				_imageLoader = new Loader();
				_imageLoader.mouseEnabled = false;
			}
			_imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadPhotoComplete);
			_imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loadPhotoError);
			_imageLoader.loadFilePromise(_mediaData);
		}

		private function clearImageLoader():void
		{
			_imageLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE,loadPhotoComplete);
			_imageLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,loadPhotoError);
		}
		
		protected function loadPhotoError(event:IOErrorEvent):void
		{
			trace("load file error");
		}
		
		protected function loadPhotoComplete(event:Event):void
		{
			
			clearImageLoader();
			trace("load pic width:" + _imageLoader.width + "  height:" + _imageLoader.height);
			if(_imageLoader.width > 500)
			{
				_imageLoader.scaleX = _imageLoader.scaleY = 500 / _imageLoader.width;
			}
			_file =_mediaData.file as FileReference;
			var file:File = new File();
			if(!weiboPic)
			{
			weiboPic = new Sprite();
			_imageLoader.x = - _imageLoader.width * 0.5;
			_imageLoader.y = - _imageLoader.height * 0.5;
			weiboPic.addChild(_imageLoader);
			var oldWie:Number = weiboPic.width;
			var oldHei:Number = weiboPic.height;
			if(oldWie < oldHei)
			{
				weiboPic.scaleX = weiboPic.scaleY = _addPicBtn.width * 0.5 / weiboPic.width;
			}else
			{
				weiboPic.scaleX = weiboPic.scaleY = _addPicBtn.height * 0.5 / weiboPic.height;
			}
			weiboPic.rotation = 90;
			weiboPic.x =  _addPicBtn.width * 0.5 - weiboPic.width * 0.25;
			weiboPic.y =  _addPicBtn.height * 0.5 - weiboPic.width * 0.25;
			var shape:Shape = new Shape();
			shape.graphics.beginFill(0);
			shape.graphics.drawCircle(0,0,30);
			shape.graphics.endFill();
			weiboPic.addChild(shape);
			_addPicBtn.addChild(weiboPic);
			}
			
		}
		
		public function set onClose(value:Function):void
		{
			_onClose = value;
		}
		
		public	function clear():void
		{
			_sina = null;
			_qq = null;
		}
		
	}
}